var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');

var laytpl = require('laytpl');

var index = require('./routes/index');
var admin = require('./routes/admin');

var app = express();

//express的消息提示中间件,用于传递登录失败的一些信息
var flash = require('express-flash');
//passport
var passport = require('passport');

var LocalStrategy = require('passport-local').Strategy;

var { sequelize } = require("./lib/db");
var User = sequelize.import("./models/user");

app.disable('x-powered-by');

laytpl.config({
  min:true,
  cache:false,
  open:'{{',
  close:'}}'
});

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '../views'));
app.engine('.html',laytpl.__express);
app.set('view engine','html');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../public')));

//这里周期只设置为20秒，为了方便测试
//secret在正式用的时候务必修改
//express中间件顺序要和下面一致

// app.use(session({secret: 'zhoulijie', cookie: { maxAge: 20000 }}));
app.use(session({
  resave: false,
  saveUninitialized: false,
  cookie: {maxAge: 24 * 60 * 60 * 1000},  //设置maxAge是1天，即1天后session和相应的cookie失效过期
  secret: 'zhoulijie'
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

/**
 * 本地验证，这里我用固定的账号密码
 * 如果你有条件，可以替换为你的MongoDB之类的数据库查询
 * DEMO的话passport官网有写，链接http://passportjs.org/docs
 */
passport.use('local', new LocalStrategy(
  function(username, password, done) {

    User.findOne({account:username}
      ,function(err, user){
          if(err){
            return done(err);
          }else{
              if(!user){
                return done(null, false, {
                    message: '用户名不存在'
                });
              }
              if (!user.account == username) {
                return done(null, false, {
                    message: '用户名不匹配'
                });
              }
              if (!user.password == password) {
                return done(null, false, {
                    message: '密码不匹配'
                });
              }
          }
      }
    );

    return done(null, user);
  }
));
//保存user对象
passport.serializeUser(function (user, done) {
  done(null, user);
});
//删除user对象
passport.deserializeUser(function (user, done) {
  done(null, user);
});

app.use('/', index);
app.use('/', admin.router);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  err.title = "404 - 页面未找到";
  res.render("404",err);
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
